<?php
include_once 'application/application.php';

class Page_apps {



    public $action;
    public $error;



    public function __construct() {
        $this->action = Arr::getValue($_POST, 'action', false);

        DB::connect();
        if (!DB::state()) {
            $this->error = DB::getError();
        }
    }

    public function __destruct() {

    }


    public function addApp() {

        $J = new JSON();
        $action = $J->readVar('action');
        $appname = mysql_escape_string($J->readVar('appname'));
        $params = array();

        if ($this->error) {
            $J->error($this->error);
            return $J;
        }

        if (!$appname) {
            $J->error('Укажите имя программы');
            return $J;
        }

        $res = DB::query("SELECT id FROM `admin_clientapps` WHERE name = '{$appname}'");
        if (!$res || !DB::state()) {
            $J->error('Ошибка при работе с базой данных');
            return $J;
        }
        if ($res->num_rows) {
            $J->error('Программа с таким именем уже добавлена ранее');
            return $J;
        }

        $q = "INSERT INTO `admin_clientapps`
                      (`id`, `name`      )
              VALUES  (NULL, '{$appname}')";
        $res = DB::query($q);
        if (!$res || !DB::state()) $J->error('Ошибка при сохранении данных');
        else $J->insertedId = DB::$mysqli->insert_id;

        $params['id'] = $J->insertedId;
        $params['name'] = $appname;
        if (class_exists('Log')) Log::Save(OPERATION::CREATE_APP, $params);

        return $J;

    }






    public function appList() {
/*
        $params = array();
        $rows = array();

        if (!$this->error) {
            $now = time();

            $to_date = Arr::getValue($_POST, 'to_date', false);
            if ($to_date) $to_date = DateTime::createFromFormat('Y-m-d', $to_date);
            if ($to_date) $to_date = $to_date->getTimestamp();
            else $to_date = $now;

            $from_date = Arr::getValue($_POST, 'from_date', false);
            if ($from_date) $from_date = DateTime::createFromFormat('Y-m-d', $from_date);
            //if (!$from_date || $from_date >= $to_date) $from_date = $to_date - (60*60*24*30); // 30 дней
            if (!$from_date || $from_date->getTimestamp() >= $to_date) $from_date = DateTime::createFromFormat('Y-m-d', '2010-01-01');
            $from_date = $from_date->getTimestamp();



            $q = "  SELECT * FROM `admin_conn_history`
                    WHERE created >= FROM_UNIXTIME({$from_date})
                    AND   created <= FROM_UNIXTIME({$to_date})
                    ORDER BY created DESC";

            $res = DB::query($q);

            if (!$res || !DB::state()) $this->error = 'Ошибка при работе с базой данных';
            else {
                while($row = mysqli_fetch_array($res, MYSQLI_ASSOC)){
                    $rows[] = $row;
                }
            }

        }

        $params['obj_types'] = getObjTypes();;
        $params['db_types'] = getClientDbTypes();
        $params['apps'] = getClientApps();
        $params['oss'] = getClientOSs();
        $params['btypes'] = getBuildTypes();


        $params['error'] = $this->error;
        $params['rows'] = $rows;
        $params['to_date'] = date('Y-m-d', $to_date);
        $params['from_date'] = date('Y-m-d', $from_date);

        $this->printOut(includeFile(APP_PAGE_PARTS.'list_ds.php', $params));

*/
    }







    public function printOut( $content = '' ) {

        include_once APP_PAGE_PARTS.'header.php';
        echo Navbar::getHorisontalBar();
        echo Auth::loginForm(true);

        $params = array(
            'leftmenu'  => Navbar::getVerticalBar('leftmenu'),//includeFile(APP_PAGE_PARTS.'leftmenu.php'),
            'content'   => $content? $content : ''
        );
        include APP_PAGE_PARTS.'columns.php';

        include_once APP_PAGE_PARTS.'footer.php';
        die();
    }



}

$page = new Page_apps();



if ($page->action) {
    if ($page->action == ACTIONS::INSTALL_ADD_APP) echo $page->addApp();

}
else  {
    if (!Auth::isLogged()) reLocate ('index.php');
    reLocate ('install.php?list_ds');
    Navbar::$expanded = 'lm-manager';
    Navbar::$active = 'list_ds';
    $page->appList();
}
?>